<?php

/**
 * 发布日志类
 */
class Log
{
	private static $_log = null;
	
    // 日志开关，默认开
    public $_switch = 'on';
    private $_state = array(
        'failed' => 0,
        'success' => 1,
        'exception' => 2
    );
    private $_log_types = array(
        '_system' => 0,
        '_action_publish' => 1,
        '_action_login' => 2,
        '_action_auth' => 3
    );
    private $_log_path = '';

	/**
	 * 单例模式
	 */
	public static function getInstance($log_path = '')
	{
		if(is_null(self::$_log)){
			return new self($log_path);
		}
		return self::$_log;
	}
	
    protected function __construct($log_path = '')
    {
        // 日志一周一个文件
        $this->_log_name = '_log_' . (date('Y_W'));
        if ($log_path) {
            $log_path = rtrim($log_path, '/');
            $this->_log_path = $log_path . '/';
        } else {
            $this->_log_path = realpath(dirname(__FILE__)) . '/log/';
        }

        clearstatcache();
        if ('on' == $this->_switch && !is_dir($this->_log_path)) {
            @mkdir($this->_log_path, 0777, true);
        }
    }

    /**
     * 记录日志
     */
    public function log($msg = '', $state = 'failed', $log_type = '_action_publish')
    {
        $message = '';
        if ('on' == $this->_switch && isset($this->_log_types[$log_type]) && isset($this->_state[$state])) {
            $message = (date('Y-m-d H:i:s')) . ' : [ ' . $msg . ' - ' . $state . ' - ' . $log_type . ' ]' . PHP_EOL;
            file_put_contents($this->_log_path . $this->_log_name, $message, FILE_APPEND);
        }
    }

}